import QQMapWX from '@/common/qqmap-wx-jssdk.js'
const app = {};

const siteInfo = {
	'id': 47,
	'from': 'wxapp',
	'version': '1.1.1',
	'root': 'https://zbz.brightace.com.cn/app/index.php',
};
app.mapKey = 'XFMBZ-Y7SKJ-JU5FP-FNLKM-LJTR7-REBAM';
/**
 * @des url
 */
app.url = function(e) {
	let iurl = '';
	iurl += siteInfo.root + '?i=' + siteInfo.id + '&t=0' + '&v=' + siteInfo.version + '&from=' + siteInfo.from;
	if(e) {
		e = e.split('/');
		iurl += '&c=' + e[0] + '&a=' + e[1] + '&m=zh_tcwq&do=' + e[2];
	}
	return iurl;
};
/**
 * @des request
 */
app.request = function(a, cb) {
  let iurl = app.url(a.url);
  if(a.noloading) {
	 return;
  }else {
	  uni.showLoading({
		title: '',
		mask: true,
	  });
  }
  uni.request({
    url: iurl,
    data: a.data || {},
    header: a.header || {},
    method: a.method || 'GET',
    success: function (ret) {
      cb(ret);
	  if(a.noloading) {
	  	 return;
	  }else {
	  uni.hideLoading();
	  }
    },
    fail: function (err) {
      uni.showToast({
        title: '服务器繁忙，请稍后重试~'
      });
    }
  })
};
/**
 * @des 登录
 */
app.getUinfo = function(wxUinfo, cb) {
	let _this = this, code = '', uname = wxUinfo.nickName, uavatar = wxUinfo.avatarUrl;
    uni.login({
		success: (ret) => {
			console.log('执行了登录流程……')
			code = ret.code;  // 获取到code
			app.request({
				url: 'entry/wxapp/Openid',
				data: { code: code },
			}, (ret) => {
				app.request({
					url: 'entry/wxapp/Login',
					data: {
						openid: ret.data.openid,
						img: uavatar,
						name: uname,
					}
				}, (ret) => {
					uni.setStorageSync('uinfo', ret.data);  // 本地存储
					cb && typeof cb == 'function' && cb(ret.data); 
				})
			})
		}
	})
};
/**
 * @des 更新本地用户信息
 */
app.updateUinfo = function(uid) {
	app.request({
		url: 'entry/wxapp/UserInfo',
		data: {user_id: uid}
	}, (ret) => {
		uni.setStorageSync('uinfo', ret.data);  // 更新本地存储
	})
}
/**
 * @des 判断对象是否为空
 */
app.isEmptyObj = function(o) {
	const a = Object.keys(o);
	return a.length ? false : true;
}
/**
 * @des 判断对象键值
 */
app.isCObj = function(o) {
	let k = '', v = '', r = true;
	if(!app.isEmptyObj(o)) {
		for(k in o) {
			if(o[k]) {
				r = true;
			}else {
				r = false;
			}
		}
	}else {
		r = false;
	}
	return r;
}
/**
 * @des 位置
 */
app.loc = function(cb) {
	const qqmapsdk = new QQMapWX({ key: app.mapKey });
	uni.getLocation({
		type: 'gcj02',
		success: (res) => {
			qqmapsdk.reverseGeocoder({
				location: {
					latitude: res.latitude,
					longitude: res.longitude,
				},
				success: (res) => {
					cb && (typeof cb === 'function') && cb({status: 1, result: res.result})
				},
				fail: function(err) {
					uni.showToast({
						title: err.message+'('+err.status+')',
						icon: 'none',
						duration: 3000,
					})
				}
			});
		},
		fail: (err) => {
			if(err.errMsg === "getLocation:fail auth deny") {
				cb({status: 0})
			}
		}
	})
}

export default app;